package com.lingjtx.common.other.helper;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.handle.ObjectPool;
import com.lingjtx.common.other.http.Call;
import com.lingjtx.common.other.http.Callback;
import com.lingjtx.common.other.http.Network;
import com.lingjtx.common.other.http.RemoteService;
import com.lingjtx.common.other.model.weixin.WeiXinTemplateMsgRequest;
import com.lingjtx.common.other.model.weixin.WeiXinTemplateMsgResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.http.HttpClient;

import static com.lingjtx.common.core.constant.RedisConfig.KEY_WEI_XIN_ACCESS_TOKEN;

public class WeiXinHelper {

    public static final Logger log = LoggerFactory.getLogger(WeiXinHelper.class);

    public static void send(WeiXinTemplateMsgRequest request, RedisOptions redis, ObjectPool<HttpClient> objectPool) {
        String accessToken = (String) redis.get(KEY_WEI_XIN_ACCESS_TOKEN);
        RemoteService service = Network.remote(RemoteService.class, objectPool);
        Call<WeiXinTemplateMsgResponse> call = service.sendWxTemplateMsg(accessToken, request);
        call.enqueue(new TemplateMsgRspCallback());
    }

    private static class TemplateMsgRspCallback implements Callback<WeiXinTemplateMsgResponse> {

        @Override
        public void onResponse(WeiXinTemplateMsgResponse response) {
            if (response != null && "ok".equals(response.getErrmsg())) {
                log.info("微信发送模板消息成功：{}", response.getMsgid());
            }
        }

        @Override
        public void onFailure(String t) {
            log.info("微信发送模板消息请求异常：{}", t);
        }
    }
}
